package com.stars.easyms.datasource.holder;

import com.stars.easyms.datasource.EasyMsDataSource;
import com.stars.easyms.datasource.bean.PageCountDelayHandleBean;
import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.Nullable;

/**
 * <p>className: EasyMsSynchronizationManager</p>
 * <p>description: 是否延迟获取count的Holder类</p>
 *
 * @author guoguifang
 * @date 2019/9/19 10:28
 * @since 1.3.2
 */
public final class EasyMsSynchronizationManager {

    private static final ThreadLocal<Boolean> SQL_SESSION_SYNCHRONIZATION_HOLDER = new NamedThreadLocal<>("Whether to enter sqlSession synchronization");

    private static final ThreadLocal<EasyMsDataSource> EASY_MS_DATA_SOURCE_SYNCHRONIZATION_HOLDER = new NamedThreadLocal<>("EasyMsDataSource synchronization");

    private static final ThreadLocal<PageCountDelayHandleBean> PAGE_COUNT_DELAY_HANDLE_BEAN_THREAD_LOCAL = new NamedThreadLocal<>("PageCountDelayHandleBean");

    public static void enterSynchronization() {
        SQL_SESSION_SYNCHRONIZATION_HOLDER.set(Boolean.TRUE);
    }

    public static boolean isSynchronization() {
        return Boolean.TRUE.equals(SQL_SESSION_SYNCHRONIZATION_HOLDER.get());
    }

    public static void setEasyMsDataSource(EasyMsDataSource easyMsDataSource) {
        EASY_MS_DATA_SOURCE_SYNCHRONIZATION_HOLDER.set(easyMsDataSource);
    }

    @Nullable
    public static EasyMsDataSource getEasyMsDataSource() {
        return EASY_MS_DATA_SOURCE_SYNCHRONIZATION_HOLDER.get();
    }

    public static void clearEasyMsDataSource() {
        EASY_MS_DATA_SOURCE_SYNCHRONIZATION_HOLDER.remove();
    }

    public static void setPageCountDelayHandleBean(PageCountDelayHandleBean bean) {
        PAGE_COUNT_DELAY_HANDLE_BEAN_THREAD_LOCAL.set(bean);
    }

    @Nullable
    public static PageCountDelayHandleBean getPageCountDelayHandleBean() {
        return PAGE_COUNT_DELAY_HANDLE_BEAN_THREAD_LOCAL.get();
    }

    public static void clearSynchronization() {
        EASY_MS_DATA_SOURCE_SYNCHRONIZATION_HOLDER.remove();
        SQL_SESSION_SYNCHRONIZATION_HOLDER.remove();
        PAGE_COUNT_DELAY_HANDLE_BEAN_THREAD_LOCAL.remove();
    }

    private EasyMsSynchronizationManager() {
    }
}